1475D - Cleaning the Phone - CodeForces Solution


binary search dp sortings two pointers *1800

Please click on ads to support us..

Python Code:

for _ in range(int(input())):
    n,m = map(int,input().split())
    a = list(map(int,input().split()))
    b = list(map(int,input().split()))
    x = []
    y = []
    for i in range(n):
        if b[i] == 1:
            x.append(a[i])
        else:
            y.append(a[i])
    x.sort(reverse=True)
    y.sort(reverse=True)
 
    t, cost = 0, 0
    p2 = -1
    ans = 210000000000
    while p2+1 < len(y) and t < m:
        p2 += 1
        t += y[p2]
        cost += 2
    if t >= m:
        ans = min(ans, cost)
    for i in range(len(x)):
        t += x[i]
        cost += 1
        while p2 >= 0 and t-y[p2]>=m:
            t -= y[p2]
            p2 -= 1
            cost -= 2
        if t >= m:
            ans = min(ans,cost)
    if ans >= 210000000000:
        print(-1)
    else:
        print(ans)

C++ Code:

#include<bits/stdc++.h>
//#define int long long
using namespace std;
const int num = 2e5 + 10,maNum = 1e9 + 5;
int ma, mi,ol,x, y, z, m, p, q, k;
int t, n, i, j;//循环变量
long long sum, ans;
int a[num];
set<int> box;
bool flag;
string s;
char ch;
vector<int> b, c;
#define pii pair<int,int>
int main()
{
	cin >> t;
	while(t--){
		b.clear(), c.clear();
		sum = 0;
		cin >> n >> m;
		for (i = 1; i <= n; i++)
		{
			cin >> a[i];
			sum += a[i];
		}
		for (i = 1; i <= n; i++)
		{
			cin >> k;
			if (k == 1)
			{
				b.push_back(a[i]);
			} else
			{
				c.push_back(a[i]);
			}
		}
		if (sum < m)
		{
			cout << -1 << endl;
			continue;
		}
		sort(b.begin(), b.end(), greater<int>());
		sort(c.begin(), c.end(), greater<int>());
		p = 0, q = 0;
		x = b.size() - 1, y = c.size() - 1;
		ans = 0;
		while (m > 0)
		{
			if (p <= x && m <= b[p])
			{
				ans++;
				m -= b[p];
				p++;
				break;
			}
			k = b[p] + b[p + 1];
			if (p < x && (q > y || (k > c[q])))
			{
				p += 2;
				m -= k;
			} else
			{
				m -= c[q];
				q++;
			}
			ans += 2;
		}
		m *= -1;
		for (i = p - 1; i >= 0; i--)
		{
			if (m >= b[i])
			{
				ans--;
				m -= b[i];
			} else break;
		}
		cout << ans << endl;
	}
	return 0;
}


Comments

Submit
0 Comments
More Questions

1006A - Adjacent Replacements
1195C - Basketball Exercise
1206A - Choose Two Numbers
1438B - Valerii Against Everyone
822A - I'm bored with life
9A - Die Roll
1430B - Barrels
279B - Books
1374B - Multiply by 2 divide by 6
1093B - Letters Rearranging
1213C - Book Reading
1468C - Berpizza
1546B - AquaMoon and Stolen String
1353C - Board Moves
902A - Visiting a Friend
299B - Ksusha the Squirrel
1647D - Madoka and the Best School in Russia
1208A - XORinacci
1539B - Love Song
22B - Bargaining Table
1490B - Balanced Remainders
264A - Escape from Stones
1506A - Strange Table
456A - Laptops
855B - Marvolo Gaunt's Ring
1454A - Special Permutation
1359A - Berland Poker
459A - Pashmak and Garden
1327B - Princesses and Princes
1450F - The Struggling Contestant